package org.iweb.ui.page;

import java.util.HashMap;
import java.util.Map;

import org.iweb.init.AbstractRegister;
import org.iweb.init.Register;
import org.iweb.init.scanner.AnnotationScanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings({ "rawtypes", "unchecked" })
@Register(name = "PageRegister")
public class PageRegister extends AbstractRegister {

	Logger log = LoggerFactory.getLogger(PageRegister.class);

	private Map<String, Class> pages;

	public void addPage(String path, Class clazz) {
		Class c = getPages().get(path);
		if (c == null) {
			getPages().put(path, clazz);
			log.debug("Register page " + clazz.getName() + " on path: " + path);
		}
	}

	public Map<String, Class> getPages() {
		if (pages == null)
			pages = new HashMap<String, Class>();
		return pages;
	}

	@Override
	public void populate(AnnotationScanner scanner) {
		Map<String, Object> annotatedClasses = scanner.getClasses().get(
				Page.class.getName());

		if (annotatedClasses != null) {
			Page ann;
			Class c;
			for (Object obj : annotatedClasses.values()) {

				if (obj instanceof Class) {
					c = (Class) obj;
					ann = (Page) c.getAnnotation(Page.class);

					if (ann.path().equalsIgnoreCase(""))
						addPage(c.getName(), c);
					else
						addPage(ann.path(), c);
				}
			}
		}

	}

	@Override
	public void clear() {
		getPages().clear();		
	}

	
	@Override
	public Long getNumReg() {
		return new Long(getPages().size());
	}
}
